package lion.json.handlers;

import java.io.IOException;
import java.io.Writer;

import lion.json.IJsonHandler;

/**
 * @author lion
 * @mail hl_0074@sina.com
 * @date 2011-9-27
 */
public class StringHandler implements IJsonHandler {

	@Override
	public void handle(Object o, Writer writer) throws IOException {

		String tmp = null;

		if (o != null) {
			if (o instanceof String) {
				tmp = (String) o;
			} else {
				tmp = String.valueOf(o);
			}

			writer.write("\"");
			escape(tmp, writer);
			writer.write("\"");
			// tmp = "\"" + StringEscapeUtils.escapeJava(tmp) + "\"";
		} else {
			writer.write("null");
		}
	}

	static void escape(String src, Writer writer) throws IOException {

		for (int i = 0; i < src.length(); i++) {
			char c = src.charAt(i);
			if (c == '"') {
				writer.write("\\\"");
			} else if (c == '\n') {
				writer.write("\\n");
			} else if (c == '\r') {
				writer.write("\\r");
			} else if (c == '\\') {
				writer.write("\\\\");
			} else if (c == '\t') {
				writer.write("\\t");
			} else if (c < '\16') {
				writer.write("\\u000");
				writer.write(Integer.toHexString(c));
			} else if (c < ' ') {
				writer.write("\\u00");
				writer.write(Integer.toHexString(c));
			} else if ((c >= '') && (c <= 160)) {
				writer.write("\\u00");
				writer.write(Integer.toHexString(c));
			} else {
				writer.write(c);
			}
		}
	}
}
